package xyj.sparrow.scheduler.server;

import xyj.sparrow.common.netty.decoder.ProtostuffDecoder;
import xyj.sparrow.common.netty.encoder.ProtostuffEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import xyj.sparrow.discovery.api.SparrowDiscovery;
import xyj.sparrow.scheduler.server.handler.IdleServerHandler;
import xyj.sparrow.scheduler.server.handler.NettyServerHandler;
import xyj.sparrow.scheduler.util.RpcServiceImplUtil;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;


/**
 * @ClassName NettyServer
 * @Description TODO
 * @Author Jim
 * @Date 2021/1/12 14:54
 * @Version 1.0.0
 **/
@Data
@Slf4j
public class NettyServer implements Runnable {
    private int port;
    @Resource
    private RpcServiceImplUtil rpcServiceImplUtil;
    @Resource
    private SparrowDiscovery sparrowDiscovery;

    public NettyServer(int port) {
        this.port = port;
    }

    @PostConstruct
    public void init() {
        log.info("NettyServer init...");
        startWithThread();
    }

    public void startWithThread() {
        Thread thread = new Thread(this);
        thread.setDaemon(true);
        thread.setName("NettyServerThread");
        thread.start();
    }

    @Override
    public void run() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();

        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("encoder", new ProtostuffEncoder());
                        ch.pipeline().addLast("decoder", new ProtostuffDecoder(1024 * 1024, 0, 4, 0, 4));
                        ch.pipeline().addLast(new IdleStateHandler(60, 0, 0));
                        NettyServerHandler nettyServerHandler = new NettyServerHandler();
                        nettyServerHandler.setRpcServiceImplUtil(rpcServiceImplUtil);
                        ch.pipeline().addLast(nettyServerHandler);
                        ch.pipeline().addLast(new IdleServerHandler());
                    }
                });
        try {
            ChannelFuture future = bootstrap.bind(port).sync();
            log.info("启动服务端（{}）...", port);
            //服务发现与注册 -->spi todo
            sparrowDiscovery.register("services", null, port, "10065");
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("", e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}
